package com.example.springlog.converter;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.example.springlog.entity.DesensitiveRule;
import com.example.springlog.util.DesensitiveUtil;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description:
 * @Author: 刘超
 * @Date: 2023-06-01 10:45
 */
public class DesensitiveMessageConverter extends MessageConverter {

    public static String DESENSITIVE_KEY = "desensitive";

    public static String DESENSITIVE_TRUE = "true";

    public static String DESENSITIVE_FALSE = "false";

    public static String DESENSITIVE_RULE = "desensitiveRule";

    @Override
    public String convert(ILoggingEvent event) {
        String formattedMessage = event.getFormattedMessage();
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        String sensitive = lc.getProperty(DESENSITIVE_KEY);
        List<DesensitiveRule> rules = (List<DesensitiveRule>) lc.getObject(DESENSITIVE_RULE);
        if (StringUtils.hasLength(sensitive) && DESENSITIVE_TRUE.equals(sensitive) && !CollectionUtils.isEmpty(rules)) {
            formattedMessage = DesensitiveUtil.desensitive(formattedMessage,rules);
        }
        return formattedMessage;
    }
}
